//
//  XQSendCodeButton.swift
//  Spark Peso
//
//  Created by 小琦 on 2025/2/4.
//

import UIKit

class XQSendCodeButton: UIButton {

    private var isDown : Bool = false
    private var timer : Timer?
    private var totalTime : Int = 60
    private var currentNumber : String?
    
    
    public func start() {
        self.isEnabled = false
        self.totalTime = 60
        currentNumber = self.title(for: .normal)
        
        updateTitle()
        
        isDown = true
        startTimer()
    }
    
    public func stop() {
        stopTimer()
        totalTime = 60
        self.isEnabled = true
        isDown = false
        setTitle(currentNumber, for: .normal)
        self.titleLabel?.font = UIFont.systemFont(ofSize: 20, weight: .medium)
    }

    
    @objc private func timeChanged() {
        if totalTime == 1 {
            setTitle("retry", for: .normal)
            setTitle("retry", for: .disabled)
            totalTime = 60
            stopTimer()
            isDown = false
            self.isEnabled = true
            self.titleLabel?.font = UIFont.systemFont(ofSize: 20, weight: .medium)
        }else {
            totalTime -= 1
            updateTitle()
        }
    }
    
    private func updateTitle() {
        let str = "\(totalTime)s"
        setTitle(str, for: .normal)
        setTitle(str, for: .disabled)
        self.titleLabel?.font = UIFont.systemFont(ofSize: 20)
    }
    
    private func startTimer() {
        timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(timeChanged), userInfo: nil, repeats: true)
        RunLoop.current.add(timer!, forMode: .common)
    }
    
    private func stopTimer() {
        if let timer = timer {
            timer.invalidate()
            self.timer = nil
        }
    }
}
